<template>
	<view class="home-container">

		
		<!-- 轮播图 -->
		<view class="banner-container">
			<swiper class="banner" indicator-dots autoplay circular interval="3000" duration="500" 
				:indicator-active-color="'#007AFF'" :indicator-color="'rgba(255, 255, 255, 0.5)'">
				<swiper-item v-for="(item, index) in bannerList" :key="index" @click="viewActivityDetail(item.id)">
					<image class="banner-image" :src="getImageUrl(item.image) || '/static/banner/banner1.png'" mode="aspectFill"></image>
					<view class="banner-title" v-if="item.title">{{item.title}}</view>
				</swiper-item>
			</swiper>
			
			<!-- 加载指示器 -->
			<view class="banner-loading" v-if="loading.banner">
				<view class="loader"></view>
			</view>
		</view>
		
	
		<!-- 最新公告 -->
		<view class="section notice-section">
			<view class="section-header">
				<view class="section-title-wrap">
					<text class="section-title">最新公告</text>
				</view>
			</view>
			
			<view class="notice-list">
				<view class="notice-card" v-if="latestNotice" @click="viewNoticeDetail(latestNotice.id)" hover-class="notice-card-hover">
					<view class="notice-content">
						<text class="notice-title">{{latestNotice.title}}</text>
						<text class="notice-text">{{truncateText(latestNotice.content, 50)}}</text>
						<view class="notice-footer">
							<text class="notice-time">{{formatDate(latestNotice.createTime)}}</text>
							<view class="read-more">查看详情 <text class="arrow">›</text></view>
						</view>
					</view>
				</view>
				
				<!-- 加载状态 -->
				<view class="loading-state" v-if="loading.notice">
					<view class="loader"></view>
				</view>
				
				<!-- 空状态 -->
				<view class="empty-state" v-if="!latestNotice && !loading.notice">
					<image src="/static/empty.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无公告信息</text>
				</view>
			</view>
		</view>
		
		<!-- 活动推荐 -->
		<view class="section activity-section">
			<view class="section-header">
				<view class="section-title-wrap">
					<text class="section-title">活动推荐</text>
				</view>
			</view>
			
			<view class="activity-list">
				<view class="activity-card" v-for="(item, index) in activityList" :key="index" 
					@click="viewActivityDetail(item.id)" hover-class="activity-card-hover">
					<image class="activity-image" :src="getImageUrl(item.cover) || '/static/default-activity.png'" mode="aspectFill"></image>
					<view class="activity-info">
						<text class="activity-title">{{item.title}}</text>
						<view class="activity-meta">
							<view class="activity-time-location">
								<view class="time-wrap">
									<uni-icons type="calendar" size="14" color="#666"></uni-icons>
									<text class="activity-time">{{formatDate(item.startTime)}}</text>
								</view>
								<view class="location-wrap" v-if="item.location">
									<uni-icons type="location" size="14" color="#666"></uni-icons>
									<text class="activity-location">{{item.location}}</text>
								</view>
							</view>
							<view class="activity-status" :class="getStatusClass(item)">
								{{getStatusText(item)}}
							</view>
						</view>
					</view>
				</view>
				
				<!-- 加载状态 -->
				<view class="loading-state" v-if="loading.activity">
					<view class="loader"></view>
				</view>
				
				<!-- 空状态 -->
				<view class="empty-state" v-if="activityList.length === 0 && !loading.activity">
					<image src="/static/empty.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无活动信息</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getLatestNotice } from '@/api/notice.js';
import { activityApi } from '@/api/activity.js';
import { getImageUrl } from '@/utils/image.js';

	export default {
		data() {
			return {
			userInfo: null,
			isLogin: false,
			bannerList: [],
			latestNotice: null,
			activityList: [],
			loading: {
				banner: true,
				notice: true,
				activity: true
			}
		}
	},
	onLoad() {
		this.checkLogin();
		this.loadData();
	},
	onShow() {
		this.checkLogin();
		// 获取全局数据
		const app = getApp();
		
		// 检查是否需要刷新数据
		if (app.globalData) {
			// 如果公告列表需要刷新
			if (app.globalData.noticeListNeedRefresh) {
				console.log('首页检测到公告变更，刷新最新公告');
				this.loadLatestNotice();
				app.globalData.noticeListNeedRefresh = false;
			}
			
			// 如果活动列表需要刷新
			if (app.globalData.activityListNeedRefresh) {
				console.log('首页检测到活动变更，刷新推荐活动');
				this.loadRecommendActivities();
				app.globalData.activityListNeedRefresh = false;
			}
			
			// 如果轮播图需要刷新
			if (app.globalData.bannerNeedRefresh) {
				console.log('首页检测到轮播图变更，刷新轮播图');
				this.loadBannerImages();
				app.globalData.bannerNeedRefresh = false;
			}
		}
	},
	onPullDownRefresh() {
		this.loadData();
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	},
	methods: {
		getImageUrl,
		// 检查登录状态
		checkLogin() {
			const token = uni.getStorageSync('token');
			const userInfo = uni.getStorageSync('userInfo');
			
			this.isLogin = !!token && !!userInfo;
			this.userInfo = userInfo || {};
		},
		
		// 加载数据
		async loadData() {
			// 重置加载状态
			this.loading = {
				banner: true,
				notice: true,
				activity: true
			};
			
			// 使用Promise.all并行加载数据
			try {
				await Promise.all([
					this.loadBannerImages(),
					this.loadLatestNotice(),
					this.loadRecommendActivities()
				]);
			} catch (error) {
				console.error('加载数据失败', error);
				uni.showToast({
					title: '加载数据失败，请下拉刷新重试',
					icon: 'none'
				});
				
				// 确保即使失败也更新加载状态
				this.loading = {
					banner: false,
					notice: false,
					activity: false
				};
			}
		},
		
		// 获取轮播图数据
		async loadBannerImages() {
			this.loading.banner = true;
			try {
				const res = await activityApi.getBannerImages();
				
				// 使用Vue的set方法确保响应式更新
				if (res.code === 200 && res.data && res.data.length > 0) {
					this.bannerList = [...res.data];
				} else {
					// 默认轮播图
					this.bannerList = [
						{ image: '/static/banner/banner1.png' },
						{ image: '/static/banner/banner2.png' },
						{ image: '/static/banner/banner3.png' }
					];
				}
				return res;
			} catch (error) {
				console.error('获取轮播图失败', error);
				// 设置默认轮播图
				this.bannerList = [
					{ image: '/static/banner/banner1.png' },
					{ image: '/static/banner/banner2.png' },
					{ image: '/static/banner/banner3.png' }
				];
				throw error;
			} finally {
				this.loading.banner = false;
			}
		},
		
		// 获取最新公告
		async loadLatestNotice() {
			this.loading.notice = true;
			try {
				const res = await getLatestNotice();
				
				if (res.code === 200 && res.data) {
					// 确保响应式更新
					this.latestNotice = JSON.parse(JSON.stringify(res.data));
				} else {
					this.latestNotice = null;
				}
				return res;
			} catch (error) {
				console.error('获取最新公告失败', error);
				this.latestNotice = null;
				throw error;
			} finally {
				this.loading.notice = false;
			}
		},
		
		// 获取推荐活动
		async loadRecommendActivities() {
			this.loading.activity = true;
			try {
				const res = await activityApi.getRecommendActivities();
				
				if (res.code === 200 && res.data) {
					// 确保响应式更新
					this.activityList = [...(res.data || [])];
				} else {
					this.activityList = [];
				}
				return res;
			} catch (error) {
				console.error('获取推荐活动失败', error);
				this.activityList = [];
				throw error;
			} finally {
				this.loading.activity = false;
			}
		},
		
		// 格式化日期
		formatDate(dateStr) {
			if (!dateStr) return '';
			
			const date = new Date(dateStr);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
		},
		
		// 获取活动状态样式
		getStatusClass(activity) {
			const now = new Date().getTime();
			const startTime = new Date(activity.startTime).getTime();
			const endTime = activity.endTime ? new Date(activity.endTime).getTime() : startTime + 86400000;
			
			if (now < startTime) {
				return 'status-upcoming';
			} else if (now >= startTime && now <= endTime) {
				return 'status-ongoing';
			} else {
				return 'status-ended';
			}
		},
		
		// 获取活动状态文本
		getStatusText(activity) {
			const now = new Date().getTime();
			const startTime = new Date(activity.startTime).getTime();
			const endTime = activity.endTime ? new Date(activity.endTime).getTime() : startTime + 86400000;
			
			if (now < startTime) {
				return '未开始';
			} else if (now >= startTime && now <= endTime) {
				return '进行中';
			} else {
				return '已结束';
			}
		},
		
		// 截断文本
		truncateText(text, length) {
			if (!text) return '';
			
			// 移除HTML标签
			const plainText = text.replace(/<[^>]+>/g, '');
			
			if (plainText.length <= length) return plainText;
			return plainText.substr(0, length) + '...';
		},
		
		// 页面导航
		navigateTo(url) {
			if (!this.isLogin && url !== '/pages/login/login') {
				uni.showModal({
					title: '提示',
					content: '请先登录',
					confirmText: '去登录',
					success: (res) => {
						if (res.confirm) {
							this.goToLogin();
						}
					}
				});
				return;
			}
			
			uni.navigateTo({
				url,
				fail: (err) => {
					console.error('页面跳转失败', err);
					uni.showToast({
						title: '页面跳转失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 跳转到登录页
		goToLogin() {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		},
		
		// 查看公告详情
		viewNoticeDetail(id) {
			uni.navigateTo({
				url: `/pages/notice/detail?id=${id}`
			});
		},
		
		// 查看活动详情
		viewActivityDetail(id) {
			if (!id) return;
			
			uni.navigateTo({
				url: `/pages/activity/detail?id=${id}`
			});
		}
		}
	}
</script>

<style lang="scss" scoped>
.home-container {
	min-height: 100vh;
	background-color: #f7f8fa;
	padding-bottom: 30rpx;
}

.status-bar {
	height: var(--status-bar-height, 0);
	width: 100%;
}

/* 轮播图样式 */
.banner-container {
	padding: 24rpx;
	position: relative;
}

.banner {
	height: 320rpx;
	border-radius: 16rpx;
	overflow: hidden;
	transform: translateY(0);
	box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.1);
	position: relative;
}

.banner-image {
	width: 100%;
	height: 100%;
	border-radius: 16rpx;
	transition: transform 0.3s ease;
}

.banner-title {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
	color: #ffffff;
	padding: 20rpx 30rpx;
	font-size: 28rpx;
	font-weight: bold;
	text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}

.banner-loading {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: rgba(255,255,255,0.7);
	border-radius: 16rpx;
}

/* 功能导航样式 */
.feature-grid {
	display: flex;
	background-color: #fff;
	padding: 30rpx 20rpx;
	margin: 0 24rpx 24rpx;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.feature-item {
	flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	transition: all 0.3s ease;
	padding: 20rpx 0;
	border-radius: 12rpx;
}

.feature-item-hover {
	background-color: rgba(0, 0, 0, 0.03);
	transform: scale(0.96);
}

.feature-icon {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	display: flex;
	justify-content: center;
	align-items: center;
	margin-bottom: 18rpx;
	color: white;
	font-size: 42rpx;
	box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}

.notice-icon {
	background: linear-gradient(135deg, #3498db, #2980b9);
}

.service-icon {
	background: linear-gradient(135deg, #2ecc71, #27ae60);
}

.activity-icon {
	background: linear-gradient(135deg, #f39c12, #e67e22);
}

.history-icon {
	background: linear-gradient(135deg, #9b59b6, #8e44ad);
}

.feature-name {
	font-size: 26rpx;
	color: #333;
	font-weight: 500;
}

/* 公共卡片样式 */
.section {
	background-color: #fff;
	margin: 0 24rpx 24rpx;
	padding: 24rpx;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 20rpx;
}

.section-title-wrap {
	position: relative;
	padding-left: 24rpx;
}

.section-title-wrap:before {
	content: '';
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	width: 8rpx;
	height: 30rpx;
	background: linear-gradient(to bottom, #007AFF, #5e9fff);
	border-radius: 4rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.view-more {
	font-size: 26rpx;
	color: #007AFF;
	display: flex;
	align-items: center;
}

/* 公告卡片样式 */
.notice-card {
	background-color: #f8f9fb;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-top: 16rpx;
	transition: all 0.3s;
	border-left: 4rpx solid #3498db;
}

.notice-card-hover {
	background-color: #f0f2f5;
	transform: translateY(2rpx);
}

.notice-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 12rpx;
	display: block;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 1;
	-webkit-box-orient: vertical;
}

.notice-text {
	font-size: 26rpx;
	color: #666;
	line-height: 1.5;
	margin-bottom: 16rpx;
	display: block;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	word-break: break-all;
}

.notice-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 24rpx;
}

.notice-time {
	color: #999;
}

.read-more {
	color: #007AFF;
	display: flex;
	align-items: center;
}

.arrow {
	margin-left: 4rpx;
	font-size: 28rpx;
}

/* 活动卡片样式 */
.activity-card {
	background-color: #fff;
	border-radius: 12rpx;
	margin-top: 24rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;
}

.activity-card-hover {
	transform: translateY(2rpx);
	box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.05);
}

.activity-image {
	width: 100%;
	height: 240rpx;
	border-top-left-radius: 12rpx;
	border-top-right-radius: 12rpx;
	transition: transform 0.6s ease;
}

.activity-card:active .activity-image {
	transform: scale(1.03);
}

.activity-info {
	padding: 20rpx;
}

.activity-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 1;
	-webkit-box-orient: vertical;
}

.activity-meta {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.activity-time-location {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.time-wrap, .location-wrap {
	display: flex;
	align-items: center;
	gap: 6rpx;
}

.activity-time, .activity-location {
	font-size: 24rpx;
	color: #666;
}

.activity-status {
	font-size: 24rpx;
	padding: 6rpx 16rpx;
	border-radius: 30rpx;
	font-weight: 500;
}

.status-upcoming {
	color: #fff;
	background: linear-gradient(to right, #3498db, #5e9fff);
}

.status-ongoing {
	color: #fff;
	background: linear-gradient(to right, #2ecc71, #4cd986);
}

.status-ended {
	color: #fff;
	background: linear-gradient(to right, #95a5a6, #7f8c8d);
}

/* 加载状态 */
.loading-state {
		display: flex;
		justify-content: center;
	align-items: center;
	padding: 40rpx 0;
}

.loader {
	width: 50rpx;
	height: 50rpx;
	border: 4rpx solid rgba(0, 122, 255, 0.1);
	border-left-color: #007AFF;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	to {
		transform: rotate(360deg);
	}
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx 0;
}

.empty-image {
	width: 180rpx;
	height: 180rpx;
	margin-bottom: 20rpx;
	opacity: 0.6;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
	letter-spacing: 2rpx;
	}
</style>
